import json

import requests

class airline():
    start_city="SZ"
    end_city="BJ"

    city = ['BJ', 'TJ', 'SH', 'NJ', 'XA', 'WH', 'ZZ', 'CS', 'XM', 'GZ', 'SZ']

    #请求
    def send(self,session,start,end,time):
        url="http:/lapi.airplane.com/check"

        param={
            "start":start,
            "end":end,
            "time":time
        }

        resp=session.get(url=url,params=param)
        resp.encoding = "utf-8"

        # 输出格式为{"available":1,"price":3000}
        result = json.loads(resp.text)

        return  result

    #计算最低价格
    def min_price(self,city,session,start_city,end_city):
        res = self.send(session, "SZ", "BJ", 1)
        min_price = res.get("price")
        l = []

        # 只转乘一次的情况
        for x in city:
            for i in range(1, 3):
                for j in range(i + 1, 4):
                    res1 = self.send(session, start_city, x, i)
                    res2 = self.send(session, x, end_city, j)
                    if res1.get("available") == 1 and res2.get("available") == 1:
                        if res1.get("price") + res2.get("price") < min_price:
                            min_price = res1.get("price") + res2.get("price")
                            l.clear()
                            l.append([start_city, x, end_city])
        # 转乘两次的情况
        for x in city:
            res1 = self.send(session, start_city, x, 1)
            if res1.get("available") == 0:
                continue
            for y in city:
                res2 = self.send(session, x, y, 2)
                res3 = self.send(session, y, end_city, 3)
                if res2.get("available") == 1 and res3.get("available") == 1:
                    if res1.get("price") + res2.get("price") + res3.get("price") < min_price:
                        min_price = res1.get("price") + res2.get("price") + res3.get("price")
                        l.clear()
                        l.append([start_city, x,y, end_city])

        return {"min_price":min_price,"airline":l}


    session=requests.session()

    #输出格式为{"min_price":min_pricel,"airline":l}
    result=min_price(city,session,start_city,end_city)
    
    print(f"最便宜的乘机方案为：{result[min_price]},价格为：{result.get(airline)}")






